<?php
/**  */

namespace backend\models;


use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;

class RoleForm extends Model
{
    public $name;

    public $description;

    public $permissions = [];

    //保存之前的角色名称
    public $prevName;

    /** 设置场景 */
    const SCENARIO_ADD = 'add';

    //const SCENARIO_DEAULT = 'add';

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        return ArrayHelper::merge($scenarios,[
            self::SCENARIO_ADD =>['name','description','permissions'],

        ]);
    }

    /**
     * 定义验证规则
     * @return array
     */
    public function rules()
    {
        return [
            [['name','description'],'required'],
            [['name'],'string','max'=>'64'],
            [['name'],'validateRole','on'=>self::SCENARIO_ADD],
            [['permissions'],'safe'],
        ];
    }

    /**
     * 自定义验证规则 验证权限属性是否存在
     * @param $attributes  '需要验证的属性的名字' string|Array
     * @param $param '参数'
     */
    public function validateRole($attributes, $param)
    {

        $auth =\Yii::$app->authManager;
        if(is_array($attributes)){
            foreach($attributes as $attribute){
                if($auth->getRole($this->$attribute)){
                    $this->addError($attribute,'角色已存在');
                }
            }
        }else{
            /** getpermission 没有对应的角色是放回空 */
            if($auth->getRole($this->$attributes)){
                $this->addError($attributes,'角色已存在');
            }
        }

    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'name'=>'名称',
            'description'=>'描述',
            'permissions'=>'权限',
        ];
    }


    /**
     * 放回指定格式的数组
     * @return array('name'=>'description')
     */
    public static function allPermissions()
    {
        $auth = \Yii::$app->authManager;

       // return $permissions = ArrayHelper::map($auth->getPermissions(),'name','description');
        return ArrayHelper::getColumn($auth->getPermissions(),'description');;

    }

    /**
     * @param $name
     * @return string
     */
    public static function getPermissions($name){
        $auth =\Yii::$app->authManager;

        $permissions = $auth->getPermissionsByRole($name);

        //$arr  =array_keys($permissions);

        //return implode(" ",$arr);
        $arr =ArrayHelper::getColumn($permissions,'description');


        return implode(" ",$arr);

        //VarDumper::dump($arr,10,true);
        //exit;

//        $auth->get
    }

    /**
     *调用该方法可以保存角色
     */
    public function saveRole(){

        $auth = \Yii::$app->authManager;
        //通过获取角色判断角色是否存在,若存在就更新,否则添加
        $result = $auth->getRole($this->name);
        //当不存在时
        if(empty($result)){
            /** @var $role  '创建角色*/
            $role = $auth->createRole($this->name);
            /** @var  $role->description  '添加描述'*/
            $role->description = $this->description;
            /** 给角色关联权限 */
            //添加角色/** 把创建的角色保存到数据库 */
            if($auth->add($role)){
                foreach($this->permissions as $permissin){
                    $auth->addChild($role,$auth->getPermission($permissin));
                }
            }else{
                return false;
            }
            return true;

        }else {
            //存在时
            //得到当前修改的角色信息
            $role = $auth->getRole($this->name);
            /** @var  $role ->description  '添加描述' */
            $role->description = $this->description;
            /** 把创建的角色保存到数据库 */
            if ($auth->update($this, $role)) {
                /** 给添加的角色关联权限 */
                //关联之前把之前的权限删除
                $auth->removeChildren($role);
                foreach ($this->permissions as $permissin) {
                    $auth->addChild($role, $auth->getPermission($permissin));
                }
            }else{
                return false;
            }
            return true;
        }


    }

    /**
     * 调用该方法加载根据角色名称获取的角色数据到表单模型中
     */
    public function loadData($name){
        $auth = \Yii::$app->authManager;
        //得到当前修改的角色信息
        $role = $auth->getRole($name);
        //把之前的数据回显到页面
        $this->name = $role->name;
        $this->description = $role->description;
        $obj = $auth->getPermissionsByRole($role->name);
        $this->permissions = array_keys($obj);
        $this->prevName =$name;

    }





}